#pragma once
#include <string>
#include <sys/types.h>
#include <sys/socket.h>

class Util
{
public:
    static int ReadLine(int sock, std::string& out)
    {
        char ch;
        while (ch != '\n')
        {
            ssize_t s = recv(sock, &ch, sizeof(ch), 0);
            if (s > 0)
            {
                if (ch == '\r')
                {
                    // 看看后面是不是\n  \r或\r\n->\n
                    recv(sock, &ch, sizeof(ch), MSG_PEEK);
                    if (ch == '\n')
                    {
                        // \r\n只读\n
                        // 窥探到就一定存在
                        recv(sock, &ch, sizeof(ch), 0);
                    }
                    else
                    {
                        ch = '\n';
                    }
                }

                // 普通字符
                // \n
                out.push_back(ch);
            }
            else if (s == 0)
            {
                return 0;
            }
            else
            {
                return -1;
            }
        }

        return out.size();
    }

    static bool CutString(const std::string& target, std::string& sub_out1, std::string& sub_out2, std::string sep)
    {
        ssize_t pos = target.find(sep);
        if (pos != std::string::npos)
        {
            sub_out1 = target.substr(0, pos);
            sub_out2 = target.substr(pos + sep.size());
            return true;
        }
        return false;
    }

private:
};